<template>
  <div v-if="nvsData">
    <div class="grid-bar">
      <div v-if="nvsData && nvsData.layout && nvsData.layout.label" class="grid-label">{{nvsData.layout.label}}</div>
        <div style="display: flex;flex-direction:row-reverse;margin-right: 10px">
          <meta-dropdown :nvs-data="nvsData"></meta-dropdown>
          <template v-if="toolbarButtons.length>0">
          <span :key = "index" style="margin-left: 5px" v-for="(buttonLayout,index) in toolbarButtons">
            <NvButton :fv-data="createToolbarFvData(buttonLayout)"
                      @define-event="handleEvent($event)"
                      ></NvButton>
            </span>
          </template>
        </div>
      </div>
    <el-table :data="nvsData.nvs"
              @current-change="handleCurrentChange"
              :row-class-name="tableRowClassName"
              highlight-current-row style="width: 100%" ref="refGrid">
      <el-table-column type="selection" ></el-table-column>
        <el-table-column :prop="fdLayout.name" :label="fdLayout.label" :key = "index" v-for="(fdLayout,index) in getInputFdLayouts()">
          <template #default="scope">
            <BaseComponent :fv-data="createFvData(fdLayout,scope.row)" @define-event="handleEvent($event)"></BaseComponent>
          </template>
        </el-table-column>
        <template  v-if="operationButtons.length>0">
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <NvButton
                link
                type="text"
                size="small"
                :fv-data="createOperationButton(fdLayout,scope.row)"
                @define-event="handleEvent($event)"
                :key="index"
                v-for="(fdLayout,index) in operationButtons"
              >
              </NvButton>
            </template>
          </el-table-column>
      </template>
    </el-table>
    <FrontPagination :nvs-data="nvsData" ref="frontPagination" v-if="nvsData.layout.pageType === ConstDef.PAGE_TYPE_PAGE && nvsData.nvs.length>10"></FrontPagination>
    <NvEntryDialog ref="nvEntryDialog"></NvEntryDialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue'
import ConstDef from '../../js/ConstDef'
import frontRuleExecutor from "../../js/frule/FrontRuleExecutor";
import NvButton from '../basic/NvButton'
import BaseComponent from '../basic/BaseComponent'
import FvData from '../../js/FvData'
import nvService from '../../api/NvService'
import cacheManage from '../../cache/CacheManage'
import { ElMessage } from 'element-plus'
import FrontPagination from './FrontPagination'
import MetaDropdown from './components/MetaDropdown'
import NvEntryDialog from '../../views/basic/NvEntryDialog'
import nvsDataUtils from '../../js/NvsDataUtils'
import NvsData from '../../js/NvsData'
export default {
  name: 'NvGrid',
  components: {
    NvEntryDialog,
    NvButton,
    BaseComponent,
    FrontPagination,
    MetaDropdown
  },
  props: {
    nvsData: {
      type: Object,
      default: null
    }
  },
  setup(props) {
    const currentInstance = getCurrentInstance();
    const currentIndex = ref(-1);
    function getCurrentIndex() {
      return currentIndex;
    }
    onMounted(() => {
      if (props.nvsData && props.nvsData.nvs.length >= 1) { currentIndex.value = 0; }
      frontRuleExecutor.executeLayoutRules(currentInstance, props.nvsData, {}, ConstDef.FRONT_RULE_MOUNTED);
    })
    watch(currentIndex, (newValue, oldValue) => {
      console.log('watch 已触发', newValue)
    })
    const toolbarButtons = computed(() => {
      return getButtonFdLayouts(ConstDef.BUTTON_POSITION_TOOLBAR).reverse();
    })
    const operationButtons = computed(() => {
      return getButtonFdLayouts(ConstDef.BUTTON_POSITION_GRID_OPERATION);
    })

    function getInputFdLayouts () {
      const fdLayouts = [];
      for (const fl of props.nvsData.layout.fdLayouts) {
        if (fl.controlType !== ConstDef.CONTROL_TYPE_BUTTON) {
          fdLayouts.push(fl);
        }
      }
      return fdLayouts;
    }

    function getButtonFdLayouts (pos) {
      const fdLayouts = [];
      for (const fl of props.nvsData.layout.fdLayouts) {
        if (fl.controlType === ConstDef.CONTROL_TYPE_BUTTON && fl.buttonPosition === pos) {
          fdLayouts.push(fl);
        }
      }
      return fdLayouts;
    }

    function createFvData(fdLayout, nv) {
      const fvData = new FvData(props.nvsData.nvs, nv, props.nvsData.nd, fdLayout.name, props.nvsData.layout, fdLayout);
      return fvData;
    }

    function createOperationButton(fdLayout, nv) {
      const fvData = new FvData(props.nvsData.nvs, nv, props.nvsData.nd, fdLayout.name, props.nvsData.layout, fdLayout);
      return fvData;
    }

    function createToolbarFvData (fdLayout) {
      const fvData = new FvData(props.nvsData.nvs, null, props.nvsData.nd, fdLayout.name, props.nvsData.layout, fdLayout);
      return fvData;
    }

    function handleCurrentChange(val) {
      console.log("handleCurrentChange", val)
      let temp = -1;
      if (props.nvsData.nvs.length >= 1) { temp = 0; }
      for (let i = 0; i < props.nvsData.nvs.length; i++) {
        if (val === props.nvsData.nvs[i]) {
          temp = i;
          break;
        }
      }
      currentIndex.value = temp;
    }
    function tableRowClassName(row) {
      if (currentInstance.refs.frontPagination) {
        return currentInstance.refs.frontPagination.tableRowClassName(row);
      } else {
        return '';
      }
    }
    return {
      currentIndex,
      getCurrentIndex,
      getInputFdLayouts,
      createFvData,
      createToolbarFvData,
      createOperationButton,
      handleCurrentChange,
      toolbarButtons,
      operationButtons,
      tableRowClassName,
      ConstDef
    }
  },
  methods: {
    getSelectedNvs() {
      return this.$refs.refGrid.getSelectionRows();
    },
    getParentLayout() {
      let parent = this.$parent();
      while (parent != null) {
        if (parent.isNvLayout) { return parent; } else { parent = parent.$parent; }
      }
      return null;
    },
    getDataSource() {
      return this.getParentLayout().getDataSource();
    },
    async handleEvent (event) {
      const fvData = event.fvData;
      const functionCode = fvData.fdLayout.functionCode;
      if (functionCode === ConstDef.FUNCTION_CODE_ADD) {
        this.addNv(event);
      } else if (functionCode === ConstDef.FUNCTION_CODE_COPY) {
        this.copyNv(event);
      } else if (functionCode === ConstDef.FUNCTION_CODE_DELETE) {
        this.deleteNv(event);
      } else if (functionCode === ConstDef.FUNCTION_CODE_ROW_EDIT) {
        this.rowEdit(event)
      } else {
        this.$emit("define-event", event);
      }
    },
    async addNv(event) {
      const commonInfo = cacheManage.getDefaultCommonInfo();
      const nvMsg = await nvService.initNv(commonInfo, this.nvsData.nd.ndCode);
      const nvs = this.nvsData.nvs;
      if (nvMsg.success) { nvs.push(nvMsg.value); }
      this.currentIndex = nvs.length - 1;
      this.$refs.refGrid.setCurrentRow(nvs[nvs.length - 1]);
    },
    async copyNv(event) {
      const fvData = event.fvData;
      const nv = fvData.getNv();
      const commonInfo = cacheManage.getDefaultCommonInfo();
      const nvMsg = await nvService.copyNv(commonInfo, this.nvsData.nd.ndCode, nv.id);
      const nvs = this.nvsData.nvs;
      if (nvMsg.success) { nvs.push(nvMsg.value); }
      this.currentIndex = nvs.length - 1;
      this.$refs.refGrid.setCurrentRow(nvs[nvs.length - 1]);
    },
    async deleteNv(event) {
      const fvData = event.fvData;
      const nv = fvData.getNv();
      if (nv === null) { return; }
      if (nv.id > 0) {
        const commonInfo = cacheManage.getDefaultCommonInfo();
        const ndCode = nv.__actualNdCode;
        const nvId = nv.id;
        const deleteMsg = await nvService.deleteNvById(commonInfo, ndCode, nvId);
        if (deleteMsg.success) {
          ElMessage({
            message: '删除成功！',
            type: 'success',
            plain: true
          })
        } else { return; }
      }
      const nvs = this.nvsData.nvs;
      let index = nvs.findIndex(function(item) {
        return item === nv;
      });
      nvs.splice(index, 1);
      if (index === nvs.length) index--;
      this.currentIndex = index;
      setTimeout(() => {
        this.$refs.refGrid.setCurrentRow(nvs[index]);
      }, 100)
    },
    async rowEdit(event) {
      const fvData = event.fvData;
      const fdLayout = fvData.fdLayout;
      let expression = fdLayout.expression;
      if (!expression) {
        ElMessage({
          type: 'error',
          message: '编辑按钮没有配置表达式',
          showClose: true
        });
      }
      expression = JSON.parse(expression);
      const layoutCode = expression.layoutCode;
      const ndCode = fvData.nd.ndCode;
      const nv = fvData.getNv();
      const ndAndLayoutMsg = await nvsDataUtils.getNdAndLayout(ndCode, layoutCode);
      if (!ndAndLayoutMsg.success) { return; }
      const nvsData = new NvsData([nv], ndAndLayoutMsg.nd, ndAndLayoutMsg.layout);
      const config = {
        ndCode,
        layoutCode,
        nvsData,
        action: "show"
      }
      this.$refs.nvEntryDialog.showDialog(config, () => {});
    }
  }
}
</script>

<style>
  .hide-row {
    display: none !important;
  }
  .show-row{
  }
  .grid-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: grey;
    margin-bottom: 10px;
  }

  .grid-label {
    text-align: left;
    padding-top: 10px;
    padding-bottom: 10px;
    padding-left: 10px;
    color: white;
  }
</style>
